package com.masterclient.app.modules.category;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.category.adapter.CategoryBrandGridAdapter;
import com.masterclient.app.modules.category.adapter.ClassOneAdapter;
import com.masterclient.app.modules.category.beans.CategoryAllIndexBean;
import com.masterclient.app.modules.category.contract.CategoryContract;
import com.masterclient.app.modules.category.contract.CategoryPresenter;
import com.masterclient.app.modules.search.SearchHistoryActivity;
import com.masterclient.app.widget.NonScrollGridView;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * 作者：sean
 * 创建时间：2017/6/7 18:04
 * 功能说明：
 */

@Route(path = AroutePath.CATEGORY_FRAGMENT)
public class CategoryFragment extends BaseFragment<CategoryPresenter> implements CategoryContract.View{

    public static String TAG = "CategoryFragment";


    List<CategoryAllIndexBean.ShCategorysBean> firstList;
    int curPosition = 0;

    CategoryBrandGridAdapter categoryGridAdapter,brandGridAdapter;
    //    BrandGridAdapter brandGridAdapter;
    CategoryAllIndexBean.ShCategorysBean dataBeen;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_category)
    ImageView ivCategory;
    @BindView(R.id.tv_all_product)
    TextView tvAllProduct;
    @BindView(R.id.noScrollCategory)
    NonScrollGridView noScrollCategory;
    @BindView(R.id.category_store_layout)
    FrameLayout categoryStoreLayout;
    @BindView(R.id.tv_brand_all)
    TextView tvBrandAll;
    @BindView(R.id.noScrollBrand)
    NonScrollGridView noScrollBrand;
    @BindView(R.id.fl_brands)
    FrameLayout flBrands;
    @BindView(R.id.swipeLayout)
    SmartRefreshLayout swipeLayout;
    @BindView(R.id.tv_refresh)
    TextView tvRefresh;
    @BindView(R.id.rl_null_net)
    RelativeLayout rlNullNet;
    @BindView(R.id.category_back)
    FrameLayout categoryBack;
    @BindView(R.id.category_search_layout)
    LinearLayout categorySearchLayout;
    @BindView(R.id.category_search)
    LinearLayout categorySearch;
    @BindView(R.id.category_search_tv)
    TextView categorySearchTv;


    private boolean first = true;
    private String pageName;

    private ClassOneAdapter classOneAdapter;
    private RxBus rxBus;

    public static CategoryFragment newInstance(String pageName) {
        CategoryFragment categoryFragment = new CategoryFragment();
        Bundle bundle = new Bundle();
        bundle.putString("page_name",pageName);
        categoryFragment.setArguments(bundle);
        return categoryFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_category, null);
    }

    public void setKeyword(String keyword){
        if (categorySearchTv != null){
            categorySearchTv.setText(keyword);
        }
    }

    @Override
    protected void initOnlyOnce() {

        pageName = getArguments().getString("page_name");
        if (!TextUtils.isEmpty(pageName)&&"main".equals(pageName)) {
            categorySearchLayout.setPadding(0, ImmersionBar.getStatusBarHeight(getActivity()),0,0);
            categoryBack.setVisibility(View.GONE);
            ((ViewGroup.MarginLayoutParams) categorySearch.getLayoutParams()).leftMargin = ScreenUtils.dp2px(16);
        }else {
            categoryBack.setVisibility(View.VISIBLE);

            categoryBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
        }
        rxBus = RxBus.$();
        swipeLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
//        categorySearchLayout.setPadding(0, ImmersionBar.getStatusBarHeight(getActivity()),0,0);
        ivCategory.getLayoutParams().height = (int) (((ScreenUtils.getScreenWidth()-ScreenUtils.dp2px(1))*11/15.0f
                - ScreenUtils.dp2px(32))*17/50.0f);
        classOneAdapter = new ClassOneAdapter();
        recyclerView.setAdapter(classOneAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        classOneAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (position != classOneAdapter.getClickPosition()) {
                if(position>curPosition){
                    if((position+2)>=0&&(position+2)<firstList.size()){
                        recyclerView.smoothScrollToPosition(position+2);
                    }
                }else {
                    if((position-2)>=0&&(position-2)<firstList.size()){
                        recyclerView.smoothScrollToPosition(position-2);
                    }
                }
                curPosition = position;
                classOneAdapter.setClickPosition(position);

//                if(position == 0){
//                    flBrands.setVisibility(View.VISIBLE);
//                }else {
//                    flBrands.setVisibility(View.GONE);
                    if (firstList.get(position) != null) {
                        getCategoryBrandList(firstList.get(position));

                        ViewTransformUtil.glideImageView(mContext,firstList.get(position).getSh_image(),ivCategory,
                                new RoundedCornersTransformation(ScreenUtils.dp2px(7),0),R.mipmap.defaults);
                    }
            }
        });
        mPresenter.getCategoryData();

        if(Config.search_term_keyword == null){
            categorySearchTv.setText(SPUtils.getInstance().getString(Config.SEARCH_HINT));
        }
        rxBus.OnEvent(rxBus.register(Config.SEARCH_HINT), new Consumer<Object>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull Object o) throws Exception {
                categorySearchTv.setText(o.toString());
            }
        });

        categorySearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, SearchHistoryActivity.class);
                if(Config.search_term_keyword != null){
                    intent.putExtra("hint_word",categorySearchTv.getText().toString().trim());
                }
                startActivity(intent);
            }
        });

        categoryGridAdapter = new CategoryBrandGridAdapter(mContext);
        brandGridAdapter = new CategoryBrandGridAdapter(mContext);
        noScrollCategory.setAdapter(categoryGridAdapter);
        noScrollBrand.setAdapter(brandGridAdapter);
        noScrollCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, CategoryDetailActivity.class);
                intent.putExtra("type","0");
                intent.putExtra("cid", firstList.get(curPosition).getSh_id());
                intent.putExtra("brand_category_id",dataBeen.getSh_childs().get(position).getSh_id());
                intent.putExtra("image",dataBeen.getSh_image());
                intent.putExtra("title", dataBeen.getSh_name());

                startActivity(intent);
            }
        });

        noScrollBrand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, CategoryDetailActivity.class);
                intent.putExtra("type","1");
                intent.putExtra("cid", firstList.get(curPosition).getSh_id());
                intent.putExtra("brand_category_id",dataBeen.getSh_brands().get(position).getSh_id());
//                intent.putExtra("postion",position);
                intent.putExtra("image",dataBeen.getSh_image());
                intent.putExtra("title", dataBeen.getSh_name());
                startActivity(intent);
            }
        });

        tvAllProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(firstList != null){
                    startActivitryWithBundle(CategoryDetailActivity.class,new String[][]{{"from","firstpage"},{"type", "0"},{"cid",firstList.get(curPosition).getSh_id()},{"title",firstList.get(curPosition).getSh_name()},{"image",firstList.get(curPosition).getSh_image()}});
                }
            }
        });
        tvBrandAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(firstList != null){
                    startActivitryWithBundle(CategoryDetailActivity.class,new String[][]{{"from","firstpage"},{"type", "1"},{"cid",firstList.get(curPosition).getSh_id()},{"title",firstList.get(curPosition).getSh_name()},{"image",firstList.get(curPosition).getSh_image()}});
                }
            }
        });

        ivCategory.setOnClickListener(v->{
            if(firstList != null){
                startActivitryWithBundle(CategoryDetailActivity.class,new String[][]{{"from","firstpage"},{"type", "0"},{"cid",firstList.get(curPosition).getSh_id()},{"title",firstList.get(curPosition).getSh_name()},{"image",firstList.get(curPosition).getSh_image()}});
            }
        });

        swipeLayout.setOnRefreshListener(refreshLayout -> {
            first = true;
            curPosition =0;
            mPresenter.getCategoryData();
        });

        tvRefresh.setOnClickListener(v->{
            first = true;
            curPosition =0;
            mPresenter.getCategoryData();
        });

        super.initOnlyOnce();
    }

    @Override
    public void onResume() {
        MobclickAgent.onEvent(mContext, "page_category");
        super.onResume();
    }

    @Override
    public void showData(List<CategoryAllIndexBean.ShCategorysBean> list) {

        if(swipeLayout != null){
            swipeLayout.finishRefresh();
        }
        rlNullNet.setVisibility(View.GONE);

//        CategoryAllIndexBean.ShCategorysBean dataBean = new CategoryAllIndexBean.ShCategorysBean();
//        dataBean.setSh_name("品牌馆");
//        list.add(0,dataBean);
        firstList = list;
        classOneAdapter.setNewData(list);
        if (first) {
            first = false;
            classOneAdapter.setClickPosition(0);
            System.out.println();
//            if(!TextUtils.isEmpty(firstList.get(0).getSh_image())){
                //App.picasso.load(firstList.get(0).getSh_image()).resize(ScreenUtils.dp2px(260),ScreenUtils.dp2px(70)).transform(new NewPicassoRoundTransform(ScreenUtils.dp2px(2))).placeholder(R.mipmap.defaults_1).error(R.mipmap.defaults_1).into(ivCategory);
                GlideUtil.displayRoundImage(mContext,firstList.get(0).getSh_image(),ivCategory,7,R.mipmap.defaults_1);
//            }
            if (firstList != null&&firstList.size()>0) {
                getCategoryBrandList(firstList.get(0));
            }
        }
    }


//    @Override
//    public void showBrandList(CategoryBrandBean.DataBean dataBean) {
//        this.dataBeen = dataBean;
//        brandGridAdapter.setList(dataBean.getSh_brands());
//    }

    @Override
    public void loadFail(String s) {
        if(swipeLayout != null){
            swipeLayout.finishRefresh(false);
        }
        if(TextUtils.isEmpty(s)){
        }else {
            showToast(s);
        }
    }

    @Override
    public void loadError(String s) {
        if(swipeLayout != null){
            swipeLayout.finishRefresh(false);
        }
        if(isVisible()){
            showToast("网络连接失败");
        }
        rlNullNet.setVisibility(View.VISIBLE);
    }

    public void  getCategoryBrandList(CategoryAllIndexBean.ShCategorysBean categorysBean){
        this.dataBeen = categorysBean;
        categoryGridAdapter.setCategoryList(dataBeen.getSh_childs());
        if (categorysBean != null && categorysBean.getSh_brands() != null && categorysBean.getSh_brands().size()>0) {
            categoryStoreLayout.setVisibility(View.VISIBLE);
            brandGridAdapter.setList(dataBeen.getSh_brands());
        }else {
            categoryStoreLayout.setVisibility(View.GONE);
            brandGridAdapter.setList(null);
        }
    }


}
